#include"phonebook.h"

PhoneBook::PhoneBook() {}
	
PhoneBook::~PhoneBook() {}
	
std::istream & operator>> (std::istream & in, PhoneBook & ph) {
	std::string first, last;
	while (in.good()) {
		in >> first >> last;
		ph.add(first, last);
	}
	return in;
}

void PhoneBook::add(std::string const & first, std::string const & last) {
	lastByFirst.insert(std::make_pair(first, last));
	firstByLast.insert(std::make_pair(last, first));
}

void PhoneBook::remove(std::string const & first, std::string const & last) {
	std::multimap<std::string, std::string>::iterator to, it;
	it = lastByFirst.lower_bound(first);
	to = lastByFirst.upper_bound(first);
	while (it != to)
		if (it -> second == last)
			lastByFirst.erase(it++);
		else
			++it;
	it = firstByLast.lower_bound(last);
	to = firstByLast.upper_bound(last);
	while (it != to)
		if (it -> second == first)
			firstByLast.erase(it++);
		else
			++it;
}

void PhoneBook::printByFirst(std::ostream & out) {
	std::multimap<std::string, std::string>::iterator to, it;
	to = lastByFirst.end();
	it = lastByFirst.begin();
	for( ; it != to; ++it)
		out << it -> first << "\t" << it -> second << std::endl;
}

void PhoneBook::printByLast(std::ostream & out) {
	std::multimap<std::string, std::string>::iterator to, it;
	to = firstByLast.end();
	it = firstByLast.begin();
	for( ; it != to; ++it)
		out << it -> first << "\t" << it -> second << std::endl;
}